#include "httpsrequest.hpp"
#include<iostream>
bool requested=false;
size_t s;
void timeout(HTTPSRequest* r,void* arg){
	printf("timeout!\n");
	*(bool*)arg=true;
}

bool invalidresponse(HTTPSRequest* r,void* arg){
	printf("invalid response!\n");
	return true;
}

bool ondata(HTTPSRequest* r,void* arg){
	auto f=supportdecompress.find(r->value.find(contentencoding)->second)->second;
	auto l=s*1.5;
	auto temp=(char*)malloc(l);
	f(decompressor,arg,s,temp,l,&s);
	temp[s]=0;
	printf("%s\n",temp);
	free(arg);
	free(temp);
	requested=true;
	return true;
}

bool onresponse(HTTPSRequest* r,void* arg){
	r->print();
	s=std::stoull(r->value.find(contentlength)->second);
	auto v=(char*)malloc(s);
	r->getdata(v,s,ondata,v);
	return true;
}

int main(){
	if(HTTPSRequest::openlib()){
		bool neterr=false;
		HTTPSRequest* r=new HTTPSRequest(timeout,&neterr,invalidresponse,
		nullptr);
		for(;;){
			std::string addr,port;
			printf("enter host address:");
			std::cin>>addr;
			printf("enter host port:");
			std::cin>>port;
			r->request(addr.c_str(),std::stoi(port),GET,"/index.html",
			HTTPSRequest::defaulttable,nullptr,0,onresponse,nullptr,true);
			while(!requested){
				r->update();
				if(neterr)goto _end_request;
			}
			requested=false;
		}
		_end_request:
		HTTPSRequest::closelib();
		return 0;
	}
	return -1;
}